<?php
namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\helpers\Utility;
use app\filter\AdminFilter;
use app\enum\EnumOther;

class BaseController extends Controller
{
// 	public $layout = 'login';
	/**
	 * @desc display html with layout
	 * @param string $view
	 */
	public function view($view = '') {
		$prepareData = $this->prepareData();
		$view = str_replace('/', '.', $view);
		$routeArray = explode('.', $view);
		$prepareData = array_merge($prepareData, array(
				'nav' => Utility::getArrayValue($routeArray, count($routeArray) == 2? 0:1),
				'menunav' => $this->menunav(),
// 				'view' => Utility::getArrayValue($routeArray, count($routeArray) == 2? 1:2, 'index')
		));
		$view = Utility::getArrayValue($routeArray, count($routeArray) == 2? 1:2, 'index');
// 		dd($prepareData);
		$me= ' 我想显示点数据库信息！';
		 $me2= ' 我还想显示点分类！';
		 $data = json_decode(json_encode($prepareData));
		 
		return $this->render($view);
// 		$this->assign('user', Saw::uname());
// 		$this->assign('DATA', $prepareData);
// 		$this->display('home_layout.html');
	}
	
	/**
	 * @desc 路由当前action对应菜单栏
	 * @date 2015-12-15
	 */
	public function menunav() {
		$action = Yii::$app->controller->action->id;
		return $action;
	}
	
	/**
	 * @desc build the base response data for template
	 * @return array base response data
	 * @author Zijie Yuan
	 * @date 2015-12-15
	 */
	public function prepareData() {
		return [
			'router'=> strtolower(Yii::$app->controller->route),
			'controller' => strtolower(Yii::$app->controller->id),
			'action' => strtolower(Yii::$app->controller->action->id),
		];
	}
	
	/**
	 * @desc 返回json数据
	 * @param $data
	 * @author liaojianwen
	 * @date 2016-11-1
	 */
	public function renderJson($data)
	{
		header('Content-type: application/json');
		echo json_encode($data);
		exit;
	}
	
	/**
	 * @desc 验证是否登录
	 * @author liaojianwen
	 * @date 2016-11-10
	 * @see \yii\web\Controller::beforeAction()
	 */
	public function beforeAction($action)
	{

		if (parent::beforeAction($action)) {
			if(!Yii::$app->user->identity){
				if(Yii::$app->deviceDetect->isMobile()){
					$this->redirect("/wap/home/login/");
				} else {
					$redirect = Yii::$app->request->get('redirect', '');
					$redirect = !empty($redirect) ? $redirect : urlencode("http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
					$this->redirect(['/site/login?redirect='.$redirect]);
				}
			} else {
				//检查authitem 是否有permission
				$auth = Yii::$app->authManager;
				$actions = $this->route;
				$userId = Yii::$app->user->id;
				if($auth->getPermission($actions)){//只判断在auth_item 的权限
					$res = $auth->checkAccess($userId, $actions);
					if(!$res){
						$this->renderJson(array(
								'Error' => 'User authentication fails'
						));
						Yii::$app->end();
					}
				}
				return true;
			}
		}
		return false;
	}
}